package com.hzpd.hainan.utils;

import android.content.res.Resources;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhaijy on 2016/8/19.
 */
public class StringUtils {
    public static boolean isEmpty(CharSequence str) {
        if (str == null || str.length() == 0)
            return true;
        else
            return false;
    }
    /**
     * check string
     */
    public static boolean isNull(String str) {
        return !(str != null && str.trim().length() > 0);
    }

    public static boolean isEmptyString(String str) {
        return !(str != null && str.trim().length() > 0);
    }

    /**
     * 判断是否为手机号码
     */
    public static boolean isPhoneNumber(String phone) {
        if (TextUtils.isEmpty(phone) || phone.length() != 11) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
        return pattern.matcher(phone).matches();
    }

    /**
     * 判断是否为整型字符串
     *
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        //+表示1个或多个（如"3"或"225"），*表示0个或多个（[0-9]*）（如""或"1"或"22"），?表示0个或1个([0-9]?)(如""或"7")
        boolean isNum = str.matches("[0-9]+");
        return isNum;
    }

    public static boolean isRent(String str) {
        //+表示1个或多个（如"3"或"225"），*表示0个或多个（[0-9]*）（如""或"1"或"22"），?表示0个或1个([0-9]?)(如""或"7")
        boolean isNum = str.matches("[0-9][.]+");
        return isNum;
    }

    /**
     * 整数，或者有一位或两位小数的数字
     *
     * @param str
     * @return
     */
    public static boolean isFloat(String str) {
        //+表示1个或多个（如"3"或"225"），*表示0个或多个（[0-9]*）（如""或"1"或"22"），?表示0个或1个([0-9]?)(如""或"7")
        boolean isNum = str.matches("^(\\-)?\\d+(\\.\\d{1,2})?$");
        if (!str.contains(".")) {
            isNum = true;
        }
        return isNum;
    }

    /**
     * 半角转换为全角
     * 说明：解决TextView中文字排版参差不齐的问题
     * 将textview中的字符全角化。即将所有的数字、字母及标点全部转为全角字符，使它们与汉字同占两个字节
     * by:liubing
     *
     * @param input
     * @return
     */
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    /**
     * 去除特殊字符或将所有中文标号替换为英文标号
     * 说明：解决TextView中文字排版参差不齐的问题
     * by:liubing
     *
     * @param str
     * @return
     */
    public static String StringFilter(String str) {
        str = str.replaceAll("【", "[").replaceAll("】", "]")
                .replaceAll("！", "!").replaceAll("：", ":")
                .replace("，", ",").replace("。", ".")
                .replace("……", "......");// 替换中文标号
        String regEx = "[『』]"; // 清除掉特殊字符
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * @param url
     * @param str
     * @return
     */
    public static String isContainWidth(String url, String str) {
        if (isNull(url)) {
            return null;
        }
        return url.indexOf("?width=") > 0 ? url : url + str;
    }

    /**
     * bytes 转成Hex
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        final char[] hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] hexChars = new char[bytes.length * 2];
        int v;
        for (int j = 0; j < bytes.length; j++) {
            v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    /**
     * 将字符串转成
     *
     * @param text
     * @return
     */
    public static String sha1hash(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(text.getBytes("UTF-8"), 0, text.length());
            byte[] sha1hash = md.digest();
            return bytesToHex(sha1hash);
        } catch (Exception e) {
            Log.e(StringUtils.class.getName(), "", e);
            return null;
        }
    }

    public static String loadRawResourceString(Resources res, int resourceId) throws IOException {
        InputStream is = res.openRawResource(resourceId);
        return loadString(is);
    }

    public static String loadAssetString(Resources res, String filename) throws IOException {
        InputStream is = res.getAssets().open(filename);
        return loadString(is);
    }

    public static String loadString(InputStream is) throws IOException {
        StringBuilder builder = new StringBuilder();
        InputStreamReader reader = new InputStreamReader(is);
        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            builder.append(buf, 0, numRead);
        }
        return builder.toString();
    }

    /**
     * 将两个String数组组合一起 并去除相同的元素
     *
     * @param a
     * @param b
     * @return
     */
    public static String[] union(String[] a, String[] b) {
        LinkedList<String> retval = new LinkedList<String>();
        for (int i = 0; i < a.length; i++) {
            retval.add(a[i]);
        }
        for (int i = 0; i < b.length; i++) {
            if (!retval.contains(b[i])) {
                retval.add(b[i]);
            }
        }
        String[] retarray = new String[retval.size()];
        retval.toArray(retarray);
        return retarray;

    }

    /**
     * 找出 两个String数组相同的部分
     *
     * @param a
     * @param b
     * @return
     */
    public static String[] intersection(String[] a, String[] b) {
        List<String> blist = Arrays.asList(b);
        LinkedList<String> retval = new LinkedList<String>();
        for (int i = 0; i < a.length; i++) {
            if (blist.contains(a[i])) {
                retval.add(a[i]);
            }
        }
        String[] retarray = new String[retval.size()];
        retval.toArray(retarray);
        return retarray;
    }

    /**
     * 字符串转换成十六进制字符串
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.toString();
    }

    /**
     * 十六进制转换字符串
     */
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * bytes转换成十六进制字符串
     */
    public static String byte2HexStr(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) hs = hs + "0" + stmp;
            else hs = hs + stmp;
            //if (n<b.length-1) hs=hs+":";
        }
        return hs.toUpperCase();
    }

    private static byte uniteBytes(String src0, String src1) {
        byte b0 = Byte.decode("0x" + src0).byteValue();
        b0 = (byte) (b0 << 4);
        byte b1 = Byte.decode("0x" + src1).byteValue();
        byte ret = (byte) (b0 | b1);
        return ret;
    }

    /**
     * 十六进制字符串转换成bytes
     */
    public static byte[] hexStr2Bytes(String src) {
        int m = 0, n = 0;
        int l = src.length() / 2;
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++) {
            m = i * 2 + 1;
            n = m + 1;
            ret[i] = uniteBytes(src.substring(i * 2, m), src.substring(m, n));
        }
        return ret;
    }

    /**
     * String的字符串转换成unicode的String
     */
    public static String stringToUnicode(String strText) throws Exception {
        char c;
        String strRet = "";
        int intAsc;
        String strHex;
        for (int i = 0; i < strText.length(); i++) {
            c = strText.charAt(i);
            intAsc = (int) c;
            strHex = Integer.toHexString(intAsc);
            if (intAsc > 128) {
                strRet += "\\u" + strHex;
            } else {
                // 低位在前面补00
                strRet += "\\u00" + strHex;
            }
        }
        return strRet;
    }

    /**
     * unicode的String转换成String的字符串
     */
    public static String unicodeToString(String hex) {
        int t = hex.length() / 6;
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < t; i++) {
            String s = hex.substring(i * 6, (i + 1) * 6);
            // 高位需要补上00再转
            String s1 = s.substring(2, 4) + "00";
            // 低位直接转
            String s2 = s.substring(4);
            // 将16进制的string转为int
            int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);
            // 将int转换为字符
            char[] chars = Character.toChars(n);
            str.append(new String(chars));
        }
        return str.toString();
    }

    /**
     * gbk的String转换成utf-8的字符串
     */
    public static String gbk2utf8(String gbk) {
        String utf8 = "";
        try {
            utf8 = new String(gbk.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return utf8;
    }


    //不能全位相同的数字和字母
    public static boolean equalStr(String numOrStr) {
        boolean flag = true;
        char str = numOrStr.charAt(0);
        for (int i = 0; i < numOrStr.length(); i++) {
            if (str != numOrStr.charAt(i)) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    // 判断是否连续的字母和数字
    public static boolean isOrderNumeric(String numOrStr) {
        boolean flag = true;// 如果全是连续数字返回true
        boolean isNumeric = true;// 如果全是数字返回true
            /*for (int i = 0; i < numOrStr.length(); i++) {
                if (!Character.isDigit(numOrStr.charAt(i))) {
					isNumeric = false;
					break;
				}
			}*/

        char[] chars = numOrStr.toCharArray();
        int[] asciiArray = new int[chars.length];


        for (int i = 0; i < chars.length; i++) {
            asciiArray[i] = (int) (chars[i]);
        }
        if (true) {// 如果全是数字则执行是否连续数字判断
            for (int i = 0; i < numOrStr.length(); i++) {
                if (i > 0) {// 判断如123456 ,abcdef
                    int num = asciiArray[i];
                    int num_ = asciiArray[i - 1] + 1;
                    if (num != num_) {
                        flag = false;
                        break;
                    }
                }
            }
        } else {
            flag = false;
        }
        return flag;
    }

    // 判断是否连续的字母和数字--递减（如：987654、876543）连续数字返回true
    public static boolean isOrderNumeric_(String numOrStr) {
        boolean flag = true;// 如果全是连续数字返回true
        boolean isNumeric = true;// 如果全是数字返回true
            /*for (int i = 0; i < numOrStr.length(); i++) {
                if (!Character.isDigit(numOrStr.charAt(i))) {
					isNumeric = false;
					break;
				}
			}*/
        char[] chars = numOrStr.toCharArray();
        int[] asciiArray = new int[chars.length];


        for (int i = 0; i < chars.length; i++) {
            asciiArray[i] = (int) (chars[i]);
        }
        if (isNumeric) {// 如果全是数字则执行是否连续数字判断
            for (int i = 0; i < asciiArray.length; i++) {
                if (i > 0) {// 判断如654321

                    int num = asciiArray[i];
                    int num_ = asciiArray[i - 1] - 1;
                    if (num != num_) {
                        flag = false;
                        break;
                    }
                }
            }
        } else {
            flag = false;
        }
        return flag;
    }

    //判断密码是否为password弱密码
    public static boolean isSimplePsw(String str) {
        Pattern pattern = Pattern.compile("password");
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    /**
     * 转换两分小数据
     *
     * @param parameter
     * @return
     */
    public static String set2DecimalPlaces(int parameter) {
        String result = "0.00";
        if (parameter <= 0) {
            return result;
        }
        String pointBefore = "0";
        String pointAfter = "00";
        if (parameter / 100 > 0) {
            pointBefore = (parameter / 100) + "";
        }
        if (parameter % 100 > 0) {
            if (parameter % 100 >= 10) {
                pointAfter = (parameter % 100) + "";
            } else {
                pointAfter = "0" + parameter % 100;
            }
        }
        result = pointBefore + "." + pointAfter;
        return result;
    }

    // 校验String  只能是数字,英文字母和中文
    public static boolean isString(String s) {
        Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$");
        Matcher m = p.matcher(s);
        return m.matches();
    }

    //是否是英文字符
    public static boolean isEnglish(String charaString) {
        return charaString.matches("^[a-zA-Z]*");
    }

    //是否是中文
    public static boolean isChinese(String charaString) {
        return charaString.matches("[\\u4E00-\\u9FA5]+");
    }

    // 检测是否包含中文
    public static boolean isContainChinese(String str) {
        String regEx = "[\\u4E00-\\u9FA5]+";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否中文
     *
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) {
            return true;
        } else if (ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS) {
            return true;
        } else if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A) {
            // CJK Unified Ideographs Extension WikipediaUnicode扩展汉字
            // CJK Unified Ideographs Extension A 中日韩统一表意文字扩展区A ; 表意文字扩充A
            // CJK Unified Ideographs Extension B 中日韩统一表意文字扩展区B
            return true;
        } else if (ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {// 通用标点
            return true;
        } else if (ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION) {
            return true;
        } else if (ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    public static String replaceChinese(String s) {
        char[] chars = s.toCharArray();
        StringBuilder builder = new StringBuilder();
        for (char c : chars) {
            if (isChinese(c)) {
                c = ',';
            }
            builder.append(c);
        }
        return builder.toString();
    }

    /**
     * 删除% & 符号
     */
    public static String removeStringFilter(String str) {
        return str.replaceAll("%", "").replaceAll("&", "").trim();
    }

    // 判断一个字符串是否都为数字，是则返回true
    public static boolean isAllDigit(String str) {
        return str.matches("[0-9]{1,}");
    }

    //判断字符串是否全为英文字母，是则返回true
//    boolean isWord=str.matches("[a-zA-Z]+");
    public static boolean isAllLetter(String str) {
        return str.matches("[a-zA-Z]+");
    }


    /**
     * 是否符合身份证校验规则
     */
    public static boolean isIDCard(String str) {
        //+表示1个或多个（如"3"或"225"），*表示0个或多个（[0-9]*）（如""或"1"或"22"），?表示0个或1个([0-9]?)(如""或"7")
        boolean isIDCard = str.matches("(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])");
        //校验最后一位
        if (isIDCard) {
            String substring = str.substring(str.length() - 1);
            return substring.equals("x") || substring.equals("X") || isAllDigit(substring);
        }
        return false;
    }


    /*********************************** 身份证验证开始 ****************************************/
    /**
     * 身份证号码验证 1、号码的结构 公民身份号码是特征组合码，由十七位数字本体码和一位校验码组成。排列顺序从左至右依次为：六位数字地址码， 八位数字出生日期码，三位数字顺序码和一位数字校验码。
     * 2、地址码(前六位数） 表示编码对象常住户口所在县(市、旗、区)的行政区划代码，按GB/T2260的规定执行。 3、出生日期码（第七位至十四位）
     * 表示编码对象出生的年、月、日，按GB/T7408的规定执行，年、月、日代码之间不用分隔符。 4、顺序码（第十五位至十七位） 表示在同一地址码所标识的区域范围内，对同年、同月、同日出生的人编定的顺序号，
     * 顺序码的奇数分配给男性，偶数分配给女性。 5、校验码（第十八位数） （1）十七位数字本体码加权求和公式 S = Sum(Ai * Wi), i = 0, ... , 16 ，先对前17位数字的权求和
     * Ai:表示第i位置上的身份证号码数字值 Wi:表示第i位置上的加权因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 （2）计算模 Y = mod(S, 11)
     * （3）通过模得到对应的校验码 Y: 0 1 2 3 4 5 6 7 8 9 10 校验码: 1 0 X 9 8 7 6 5 4 3 2
     */

    public static String IDCardValidate(String ID) {
        String IDStr = ID.toLowerCase();
        String errorInfo = "";// 记录错误信息
        String[] ValCodeArr = {"1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2"};
        String[] Wi = {"7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2"};
        String Ai = "";
        // ================ 号码的长度 15位或18位 ================
        if (/*IDStr.length() != 15 && */IDStr.length() != 18) {
//            errorInfo = "身份证号码长度应该为15位或18位。";
            errorInfo = "身份证号码长度应该为18位。";
            return errorInfo;
        }
        // =======================(end)========================

        // ================ 数字 除最后以为都为数字 ================
        if (IDStr.length() == 18) {
            Ai = IDStr.substring(0, 17);
        } /*else if (IDStr.length() == 15) {
            Ai = IDStr.substring(0, 6) + "19" + IDStr.substring(6, 15);
        }*/
        if (isNumeric(Ai) == false) {
            errorInfo = "身份证15位号码都应为数字 ; 18位号码除最后一位外，都应为数字。";
            return errorInfo;
        }
        // =======================(end)========================

        // ================ 出生年月是否有效 ================
        String strYear = Ai.substring(6, 10);// 年份
        String strMonth = Ai.substring(10, 12);// 月份
        String strDay = Ai.substring(12, 14);// 月份
        if (isDataFormat(strYear + "-" + strMonth + "-" + strDay) == false) {
            errorInfo = "身份证生日无效。";
            return errorInfo;
        }
        GregorianCalendar gc = new GregorianCalendar();
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150 || (gc.getTime().getTime() - s.parse(strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {
                errorInfo = "身份证生日不在有效范围。";
                return errorInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {
            errorInfo = "身份证月份无效";
            return errorInfo;
        }
        if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
            errorInfo = "身份证日期无效";
            return errorInfo;
        }
        // =====================(end)=====================

        // ================ 地区码时候有效 ================
        Hashtable h = GetAreaCode();
        if (h.get(Ai.substring(0, 2)) == null) {
            errorInfo = "身份证地区编码错误。";
            return errorInfo;
        }
        // ==============================================

        // ================ 判断最后一位的值 ================
        int TotalmulAiWi = 0;
        for (int i = 0; i < 17; i++) {
            TotalmulAiWi = TotalmulAiWi + Integer.parseInt(String.valueOf(Ai.charAt(i))) * Integer.parseInt(Wi[i]);
        }
        int modValue = TotalmulAiWi % 11;
        String strVerifyCode = ValCodeArr[modValue];
        Ai = Ai + strVerifyCode;

        if (IDStr.length() == 18) {
            if (Ai.equals(IDStr) == false) {
                errorInfo = "身份证无效，不是合法的身份证号码";
                return errorInfo;
            }
        } else {
            return "";
        }
        // =====================(end)=====================
        return "";
    }

    public static boolean isDataFormat(String str) {
        boolean flag = false;
        // String regxStr="[1-9][0-9]{3}-[0-1][0-2]-((0[1-9])|([12][0-9])|(3[a01]))";
        String regxStr = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";
        Pattern pattern1 = Pattern.compile(regxStr);
        Matcher isNo = pattern1.matcher(str);
        if (isNo.matches()) {
            flag = true;
        }
        return flag;
    }


    private static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (isNum.matches()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isNumberAndLetter(String str) {
        Pattern pattern = Pattern.compile("[a-zA-Z0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (isNum.matches()) {
            return true;
        } else {
            return false;
        }
    }

    private static Hashtable GetAreaCode() {
        Hashtable hashtable = new Hashtable();
        hashtable.put("11", "北京");
        hashtable.put("12", "天津");
        hashtable.put("13", "河北");
        hashtable.put("14", "山西");
        hashtable.put("15", "内蒙古");
        hashtable.put("21", "辽宁");
        hashtable.put("22", "吉林");
        hashtable.put("23", "黑龙江");
        hashtable.put("31", "上海");
        hashtable.put("32", "江苏");
        hashtable.put("33", "浙江");
        hashtable.put("34", "安徽");
        hashtable.put("35", "福建");
        hashtable.put("36", "江西");
        hashtable.put("37", "山东");
        hashtable.put("41", "河南");
        hashtable.put("42", "湖北");
        hashtable.put("43", "湖南");
        hashtable.put("44", "广东");
        hashtable.put("45", "广西");
        hashtable.put("46", "海南");
        hashtable.put("50", "重庆");
        hashtable.put("51", "四川");
        hashtable.put("52", "贵州");
        hashtable.put("53", "云南");
        hashtable.put("54", "西藏");
        hashtable.put("61", "陕西");
        hashtable.put("62", "甘肃");
        hashtable.put("63", "青海");
        hashtable.put("64", "宁夏");
        hashtable.put("65", "新疆");
        hashtable.put("71", "台湾");
        hashtable.put("81", "香港");
        hashtable.put("82", "澳门");
        hashtable.put("91", "国外");
        return hashtable;
    }


    /**
     * 判断是否为银行卡   需为16位数字到19位数字之间
     */
    public static boolean isBankCardNum(String num) {
        return num.matches("^[0-9]{16,19}$");
    }

    /**
     * 截取字符串中的数字， 默认返回0
     *
     * @author 高瑞
     */
    public static int parseIntFromStr(String str) {
        if (str == null) {
            return 0;
        }

        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            String value = matcher.group(0);
            return Integer.parseInt(value);
        }
        return 0;
    }

    /**
     * 判断字符串是否包含中文
     *
     * @param str
     * @return
     */
    public static boolean isContainsChinese(String str) {
        String regEx = "[\u4e00-\u9fa5]";
        Pattern pat = Pattern.compile(regEx);
        Matcher matcher = pat.matcher(str);
        boolean flg = false;
        if (matcher.find()) {
            flg = true;
        }
        return flg;
    }

    public static SpannableStringBuilder formatStringColor(String changeString, String changerColor) {
        SpannableStringBuilder builder = new SpannableStringBuilder();
        SpannableString changeSpannableString = new SpannableString(changeString);
        changeSpannableString.setSpan(new ForegroundColorSpan(Color.parseColor(changerColor)), 0, changeSpannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.append(changeSpannableString);
        return builder;
    }


    /**
     * 判断是否包含部分特殊字符
     */
    public static boolean isContainEspecialText(String str) {
        boolean isContainEspecialText = str.matches("[^！!%%&'’,，;；=?？￥$]+");
        return isContainEspecialText;
    }

    /**
     * 四舍五入
     *
     * @param num   数值
     * @param digit 保留小数点位数
     * @return
     */
    public static double myRound(double num, int digit) {
        if (num == 0) {
            return 0;
        }
        BigDecimal b = new BigDecimal(num);
        num = b.setScale(digit, BigDecimal.ROUND_HALF_UP).doubleValue();
        return num;
    }

    /**
     * byte[]数组转换为16进制的字符串。
     *
     * @param data
     *            要转换的字节数组。
     * @return 转换后的结果。
     */
    public static final String byteArrayToHexString(byte[] data) {

        StringBuilder sb = new StringBuilder(data.length * 2);
        for (byte b : data) {
            int v = b & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase(Locale.getDefault());
    }

    /**
     * 16进制表示的字符串转换为字节数组。
     *
     * @param s
     *            16进制表示的字符串
     * @return byte[] 字节数组
     */
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] d = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个进制字节
            d[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
                    .digit(s.charAt(i + 1), 16));
        }
        return d;
    }

}
